<template>
  <div class="content-list">
    <!-- 页头 -->
    <header class="header">
      <div class="container">
        <div class="header-inner">
          <!-- 返回箭头 -->
          <div class="back-arrow" @click="handleBack">
            <svg
              xmlns="http://www.w3.org/2000/svg"
              fill="none"
              viewBox="0 0 24 24"
              stroke-width="1.5"
              stroke="currentColor"
              class="icon"
              style="width: 18px; height: 18px;"
            >
              <path
                stroke-linecap="round"
                stroke-linejoin="round"
                d="M10.5 19.5L3 12m0 0l7.5-7.5M3 12h18"
              />
            </svg>
            <h1 class="list-title">全部</h1>
          </div>
          
          <!-- 分类筛选 -->
          <div class="category-filter">
            <button 
              v-for="category in categories" 
              :key="category.id"
              :class="['category-btn', activeCategory === category.id ? 'active' : '']"
              @click="activeCategory = category.id"
            >
              {{ category.name }}
            </button>
          </div>
          
          <!-- 搜索和排序 -->
          <div class="search-sort">
            <div class="search-box">
              <input 
                type="text" 
                v-model="searchQuery" 
                placeholder="搜索作品..." 
                @keyup.enter="filterContent"
              >
              <button @click="filterContent">
                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor">
                  <path fill-rule="evenodd" d="M8 4a4 4 0 100 8 4 4 0 000-8zM2 8a6 6 0 1110.89 3.476l4.817 4.817a1 1 0 01-1.414 1.414l-4.816-4.816A6 6 0 012 8z" clip-rule="evenodd" />
                </svg>
              </button>
            </div>
            
            <div class="sort-box">
              <select v-model="sortOption" @change="sortContent">
                <option value="newest">最新发布</option>
                <option value="popular">最受欢迎</option>
                <option value="alphabetical">按标题排序</option>
              </select>
            </div>
          </div>
        </div>
      </div>
    </header>
    
    <!-- 内容区域 -->
    <main class="main-content">
      <div class="container">
        <!-- 内容卡片列表 -->
        <div class="card-grid">
          <!-- 骨架屏加载状态 -->
          <div v-if="isLoading" class="skeleton-card" v-for="i in 10" :key="i"></div>
          
          <!-- 内容卡片 -->
          <div 
            v-else
            class="content-card" 
            v-for="(item, index) in filteredContent" 
            :key="item.id"
            @click="handleCardClick(item)"
          >
            <div class="card-inner">
              <div class="cover" :style="{ backgroundImage: `url(${item.cover})` }">
                <div class="cover-overlay"></div>
                <div class="category-tag">{{ item.category }}</div>
              </div>
              <div class="card-content">
                <h3 class="title">{{ item.title }}</h3>
                <div class="user-info">
                  <div class="avatar" :style="{ backgroundImage: `url(${item.avatar})` }" @click.stop="goUserPage(item)"></div>
                  <div class="nickname" @click.stop="goUserPage(item)">{{ item.nickname }}</div>
                </div>
                <div class="stats">
                  <span class="like-count">
                    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor">
                      <path fill-rule="evenodd" d="M3.172 5.172a4 4 0 015.656 0L10 6.343l1.172-1.171a4 4 0 115.656 5.656L10 17.657l-6.828-6.829a4 4 0 010-5.656z" clip-rule="evenodd" />
                    </svg>
                    {{ item.likes }}
                  </span>
                  <span class="comment-count">
                    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor">
                      <path d="M2 5a2 2 0 012-2h7a2 2 0 012 2v4a2 2 0 01-2 2H9l-3 3v-3H4a2 2 0 01-2-2V5z" />
                    </svg>
                    {{ item.comments }}
                  </span>
                </div>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 空状态 -->
        <div v-if="filteredContent.length === 0 && !isLoading" class="empty-state">
          <div class="empty-icon">
            <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor">
              <path fill-rule="evenodd" d="M4 3a2 2 0 00-2 2v10a2 2 0 002 2h12a2 2 0 002-2V5a2 2 0 00-2-2H4zm12 12H4l4-8 3 6 2-4 3 6z" clip-rule="evenodd" />
            </svg>
          </div>
          <h3>暂无相关作品</h3>
          <p>尝试更改筛选条件或搜索其他内容</p>
          <button class="reset-btn" @click="resetFilters">重置筛选</button>
        </div>
        
        <!-- 加载更多 -->
        <div v-if="!isLoading && filteredContent.length > 0" class="load-more">
          <button @click="loadMore" :disabled="isLoadingMore">
            {{ isLoadingMore ? '加载中...' : '加载更多' }}
          </button>
        </div>
      </div>
    </main>
    
    <!-- 页脚 -->
    <footer class="footer">
      <div class="container">
        <p>© 2023 作品展示平台. 保留所有权利.</p>
        <div class="footer-links">
          <a href="#">关于我们</a>
          <a href="#">使用条款</a>
          <a href="#">隐私政策</a>
          <a href="#">联系我们</a>
        </div>
      </div>
    </footer>
  </div>
</template>

<script setup>
import { post } from '@/utils/api';
import { computed, onMounted, ref, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';

const route = useRoute();
const router = useRouter();

const categories = [
  { id: 'all', name: '全部' },
  { id:'notice',name:'校园通知'},
  { id: 'hot', name: '热点话题' },
  { id: 'activity', name: '活动信息' },
  { id: 'market', name: '跳蚤市场' },
  { id: 'study', name: '学习区' }
];

// 当前分类
const activeCategory = ref('all');

// 根据路由参数设置默认分类
onMounted(() => {
  const categoryMap = {
    '全部': 'art',
    '校园通知': 'notice',
    '热点话题': 'hot',
    '活动信息': 'activity',
    '跳蚤市场': 'market',
    '学习区': 'study'
  };

  const defaultCategory = categoryMap[route.params.category] || 'all';
  activeCategory.value = defaultCategory;
});

const contentList = ref([]);
const searchQuery = ref('');
const sortOption = ref('newest');
const isLoading = ref(true);
const isLoadingMore = ref(false);
const pageSize = ref(30);
const currentPage = ref(1);
const total = ref(0);

// 加载数据（分页、分类、搜索）
const fetchContent = async (reset = false) => {
  isLoading.value = true;
  try {
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value,
      category: activeCategory.value !== 'all' ? activeCategory.value : undefined,
      search: searchQuery.value || undefined
    };
    const res = await post.getPaged(params);
    if (reset) {
      contentList.value = [];
    }
    // 合并去重
    const newPosts = (res.posts || []).map(item => ({
      id: item._id || item.id,
      title: item.title,
      nickname: item.author?.nickname || '',
      avatar: item.author?.avatar || '/default-avatar.png',
      authorId: item.author?._id || item.authorId || '',
      cover: item.cover,
      category: item.category,
      likes: item.likes,
      comments: Array.isArray(item.comments) ? item.comments.length : (item.comments || 0),
      date: item.createdAt ? new Date(item.createdAt).toISOString().slice(0, 10) : '',
    }));
    // 前端已加载的内容去重合并
    const ids = new Set(contentList.value.map(i => i.id));
    const merged = reset ? newPosts : [...contentList.value, ...newPosts.filter(i => !ids.has(i.id))];
    contentList.value = merged;
    total.value = res.total || merged.length;
  } catch (e) {
    // 错误处理
  } finally {
    isLoading.value = false;
    isLoadingMore.value = false;
  }
};

// 首次加载
onMounted(() => {
  fetchContent(true);
});

// 分类/搜索/排序变化时重置并拉取新数据
watch([activeCategory, searchQuery, sortOption], () => {
  currentPage.value = 1;
  fetchContent(true);
});

// 加载更多
const loadMore = async () => {
  if (isLoadingMore.value) return;
  isLoadingMore.value = true;
  currentPage.value++;
  await fetchContent();
};

// 搜索时先在前端已加载数据中筛选，若不足30条再请求后端补足
const filterContent = async () => {
  currentPage.value = 1;
  isLoading.value = true;
  // 前端本地筛选
  let local = contentList.value.filter(item => {
    const query = searchQuery.value.toLowerCase();
    return (
      item.title.toLowerCase().includes(query) ||
      item.nickname.toLowerCase().includes(query) ||
      item.category.toLowerCase().includes(query)
    );
  });
  if (local.length < pageSize.value) {
    await fetchContent(true); // 拉取后端补足
    local = contentList.value.filter(item => {
      const query = searchQuery.value.toLowerCase();
      return (
        item.title.toLowerCase().includes(query) ||
        item.nickname.toLowerCase().includes(query) ||
        item.category.toLowerCase().includes(query)
      );
    });
  }
  isLoading.value = false;
};

// 排序内容
const sortContent = () => {
  currentPage.value = 1;
  // 模拟加载延迟
  isLoading.value = true;
  setTimeout(() => {
    isLoading.value = false;
  }, 500);
};

// filteredContent 只展示当前页的30条
const filteredContent = computed(() => {
  let result = [...contentList.value];
  
  // 分类筛选（根据 activeCategory 过滤）
  if (activeCategory.value !== 'all') {
    const selectedCategory = categories.find(cat => cat.id === activeCategory.value);
    if (selectedCategory) {
      result = result.filter(item => item.category === selectedCategory.name);
    }
  }
  
  // 搜索筛选
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase();
    result = result.filter(item => 
      item.title.toLowerCase().includes(query) || 
      item.nickname.toLowerCase().includes(query) ||
      item.category.toLowerCase().includes(query)
    );
  }
  
  // 排序
  switch (sortOption.value) {
    case 'newest':
      result.sort((a, b) => new Date(b.date) - new Date(a.date));
      break;
    case 'popular':
      result.sort((a, b) => b.likes - a.likes);
      break;
    case 'alphabetical':
      result.sort((a, b) => a.title.localeCompare(b.title));
      break;
  }
  
  return result.slice(0, pageSize.value * currentPage.value);
});

// 处理返回
const handleBack = () => {
  window.history.back();
};

// 处理卡片点击
const handleCardClick = (item) => {
  router.push({
    name: 'Detail',
    params: { id: item.id }
  });
};

// 跳转用户主页
const goUserPage = (item) => {
  if (item.authorId) {
    router.push(`/user/${item.authorId}`);
  }
};

// 重置筛选
const resetFilters = () => {
  activeCategory.value = 'all';
  searchQuery.value = '';
  sortOption.value = 'newest';
  filterContent();
};

// 监听搜索框变化
watch(searchQuery, (newVal, oldVal) => {
  if (newVal !== oldVal) {
    filterContent();
  }
});

// 初始化加载
onMounted(() => {
  // 模拟数据加载
  setTimeout(() => {
    isLoading.value = false;
  }, 800);
});
</script>

<style scoped>
/* 全局样式 */
:root {
  --primary-color: #1a73e8;
  --secondary-color: #34a853;
  --accent-color: #fbbc04;
  --error-color: #ea4335;
  --neutral-100: #f8f9fa;  /* 浅灰色背景 */
  --neutral-200: #e8eaed;
  --neutral-300: #dadce0;
  --neutral-400: #bdc1c6;
  --neutral-500: #9aa0a6;
  --neutral-600: #70757a;
  --neutral-700: #5f6368;
  --neutral-800: #3c4043;
  --neutral-900: #202124;
}

body {
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif;
  margin: 0;
  padding: 0;
  background-color: var(--neutral-100);  /* 浅灰色背景 */
  color: var(--neutral-800);
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 16px;
}

/* 页头 */
.header {
  background-color: #f8f7f7;  /* 白色背景 */
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.08);  /* 阴影增强视觉层次 */
  padding: 20px 0;
  position: sticky;
  top: 0;
  z-index: 100;
}

.header-inner {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.back-arrow {
  cursor: pointer;
  color: var(--neutral-700);
  transition: color 0.2s;
  display: flex;
  align-items: center;
  gap: 10px;
}

.back-arrow:hover {
  color: var(--primary-color);
}

.list-title {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: var(--neutral-900);
}

/* 分类筛选 */
.category-filter {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  background-color: #fff;  /* 白色背景与页面区分 */
  padding: 12px;
  border-radius: 12px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
}

.category-btn {
  background-color: var(--neutral-100);  /* 浅灰色按钮背景 */
  color: var(--neutral-700);
  border: 1px solid var(--neutral-200);
  border-radius: 20px;
  padding: 6px 14px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.2s;
}

.category-btn:hover {
  background-color: var(--neutral-200);
  border-color: var(--neutral-300);
}

.category-btn.active {
  background-color: var(--primary-color);
  color: #949494;
  border-color: var(--primary-color);
}

/* 搜索和排序 */
.search-sort {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  align-items: center;
}

.search-box {
  flex: 1;
  max-width: 400px;
  display: flex;
  border: 1px solid var(--neutral-300);
  border-radius: 24px;
  overflow: hidden;
  transition: border-color 0.2s;
  background-color: #fff;  /* 白色背景 */
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
}

.search-box:hover,
.search-box:focus-within {
  border-color: var(--primary-color);
}

.search-box input {
  flex: 1;
  padding: 12px 16px;
  border: none;
  outline: none;
  font-size: 14px;
  background-color: transparent;
}

.search-box button {
  background-color: #e8e8e8;
  color: #f8f8f8;
  border: none;
  padding: 12px 16px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.search-box button:hover {
  background-color: #dcdcdc;
}

.sort-box select {
  padding: 12px 16px;
  border: 1px solid var(--neutral-300);
  border-radius: 24px;
  outline: none;
  font-size: 14px;
  background-color: #fff;  /* 白色背景 */
  cursor: pointer;
  transition: border-color 0.2s;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
}

.sort-box select:hover,
.sort-box select:focus {
  border-color: var(--primary-color);
}

/* 内容区域 */
.main-content {
  padding: 32px 0;
}

.card-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 24px;
}

/* 内容卡片 */
.content-card {
  background-color: #fff;  /* 白色卡片背景 */
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);  /* 增强阴影 */
  transition: transform 0.3s, box-shadow 0.3s;
  cursor: pointer;
}

.content-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
}

.card-inner {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.cover {
  height: 180px;
  background-size: cover;
  background-position: center;
  position: relative;
  overflow: hidden;
}

.cover-overlay {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 50%;
  background: linear-gradient(to top, rgba(0, 0, 0, 0.6), transparent);
}

.category-tag {
  position: absolute;
  top: 12px;
  right: 12px;
  background-color: var(--primary-color);
  color: #fff;
  border-radius: 16px;
  padding: 4px 8px;
  font-size: 12px;
  z-index: 1;
}

.card-content {
  padding: 16px;
  flex: 1;
  display: flex;
  flex-direction: column;
}

.title {
  margin: 0 0 12px;
  font-size: 18px;
  font-weight: 600;
  color: var(--neutral-900);
  line-height: 1.3;
}

.user-info {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}

.avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  background-size: cover;
  background-position: center;
  margin-right: 8px;
}

.nickname {
  font-size: 14px;
  color: var(--neutral-700);
}

.stats {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-top: auto;
  color: var(--neutral-600);
  font-size: 13px;
}

.stats svg {
  width: 16px;
  height: 16px;
  margin-right: 4px;
  vertical-align: middle;
}

/* 骨架屏 */
.skeleton-card {
  background-color: #fff;  /* 白色背景 */
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.08);
  animation: pulse 1.5s cubic-bezier(0.4, 0, 0.6, 1) infinite;
}

.skeleton-cover {
  height: 180px;
  background-color: var(--neutral-200);
}

.skeleton-content {
  padding: 16px;
}

.skeleton-line {
  height: 16px;
  background-color: var(--neutral-200);
  margin-bottom: 8px;
  border-radius: 4px;
}

.skeleton-line.short {
  width: 60%;
}

.skeleton-line.medium {
  width: 80%;
}

@keyframes pulse {
  0%, 100% {
    opacity: 1;
  }
  50% {
    opacity: 0.7;
  }
}

/* 空状态 */
.empty-state {
  text-align: center;
  padding: 48px 0;
  background-color: #fff;  /* 白色背景 */
  border-radius: 12px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.05);
}

.empty-icon {
  width: 80px;
  height: 80px;
  background-color: var(--neutral-100);  /* 浅灰色背景 */
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 auto 24px;
}

.empty-icon svg {
  width: 40px;
  height: 40px;
  color: var(--neutral-500);
}

.empty-state h3 {
  font-size: 20px;
  font-weight: 500;
  color: var(--neutral-800);
  margin: 0 0 12px;
}

.empty-state p {
  font-size: 16px;
  color: var(--neutral-600);
  margin: 0 0 24px;
}

.reset-btn {
  background-color: var(--primary-color);
  color: #fff;
  border: none;
  border-radius: 24px;
  padding: 10px 24px;
  font-size: 16px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.reset-btn:hover {
  background-color: #0d47a1;
}

/* 加载更多按钮 */
.load-more {
  text-align: center;
  margin-top: 48px;
}

.load-more button {
  background-color: var(--primary-color);
  color: #fff;
  border: none;
  border-radius: 24px;
  padding: 12px 32px;
  font-size: 16px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.load-more button:hover {
  background-color: #0d47a1;
}

.load-more button:disabled {
  background-color: var(--neutral-400);
  cursor: not-allowed;
}

/* 页脚 */
.footer {
  background-color: #fff;  /* 白色背景 */
  border-top: 1px solid var(--neutral-200);
  padding: 24px 0;
  margin-top: 48px;
}

.footer .container {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 16px;
}

.footer p {
  margin: 0;
  font-size: 14px;
  color: var(--neutral-600);
}

.footer-links {
  display: flex;
  gap: 24px;
}

.footer-links a {
  color: var(--neutral-600);
  font-size: 14px;
  text-decoration: none;
  transition: color 0.2s;
}

.footer-links a:hover {
  color: var(--primary-color);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .header .container {
    gap: 12px;
  }
  
  .list-title {
    font-size: 20px;
  }
  
  .search-sort {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-box {
    max-width: 100%;
  }
  
  .card-grid {
    grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
    gap: 16px;
  }
  
  .content-card {
    border-radius: 8px;
  }
  
  .cover {
    height: 160px;
  }
  
  .card-content {
    padding: 12px;
  }
  
  .title {
    font-size: 16px;
  }
  
  .empty-state {
    padding: 32px 0;
  }
  
  .empty-icon {
    width: 64px;
    height: 64px;
  }
  
  .empty-icon svg {
    width: 32px;
    height: 32px;
  }
  
  .empty-state h3 {
    font-size: 18px;
  }
  
  .empty-state p {
    font-size: 14px;
  }
  
  .reset-btn {
    font-size: 14px;
    padding: 8px 20px;
  }
  
  .load-more {
    margin-top: 32px;
  }
  
  .load-more button {
    font-size: 14px;
    padding: 10px 24px;
  }
  
  .footer {
    margin-top: 32px;
  }
}
</style>